package com.his.struts.action;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.his.struts.dao.help.ConnectsDao;
import com.his.struts.dao.help.ConnectsImp;
import com.his.struts.form.ConnectForm;

/**
 * “联系我们”类
 * 
 * @author mlxnle
 * 
 */
public class ConnectAction extends DispatchAction {
	ConnectsDao db = new ConnectsImp();
	Logger log = Logger.getLogger(ConnectAction.class);
	/**
	 * 更新“联系我们”信息
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward updateConnect(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		HttpSession session = request.getSession();
		ConnectForm connectForm = (ConnectForm) form;
		if (connectForm.getPirture().getFileSize() != 0) {
			String pname = connectForm.getPirture().getFileName();
			// 图片还没得到
			String imgurl = request.getRealPath("images/" + pname);
			connectForm.setAddimg("images/" + pname);
			try {
				InputStream input = connectForm.getPirture().getInputStream();
				OutputStream output = new FileOutputStream(imgurl);
				IOUtils.copy(input, output);
				input.close();
				output.close();
			} catch (IOException e) {
				log.error(e.getMessage());
			}
			db.updateImg(connectForm);
		}
		if (null != connectForm.getBusLine()
				&& null != connectForm.getAddress()
				&& null != connectForm.getPhone()) {
			db.updateCon(connectForm);
		}
		ConnectForm connectFor = db.getShowCon();
		session.setAttribute("connectInfo", connectForm);
		ActionForward forward = mapping.findForward("bgedit");
		request.setAttribute("message", "修改成功");
		return forward;
	}

	/**
	 * 显示“联系我们”信息
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward showConnect(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		HttpSession session = request.getSession();
		ActionForward forward = null;
		String forwhere = request.getParameter("forwhere");
		ConnectForm connectForm = db.getShowCon();
		session.setAttribute("connectInfo", connectForm);
		if (null != forwhere) {
			forward = mapping.findForward("bgedit");
		} else {
			forward = mapping.findForward("success");
		}
		return forward;
	}
}